package com.library.controller;

import com.library.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.library.entity.*;

import com.library.dao.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * LoginController
 * 处理在login.jsp页面的请求
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @GetMapping("/login")
    public String login(Model model,
                        @CookieValue(value = "loginUser", required = false) String loginUser,
                        @CookieValue(value = "userName", required = false) String userName,
                        HttpSession session) {
        model.addAttribute("mode", "user");
        if (session.getAttribute("role") == null && loginUser != null) {
            User user = loginService.findUserByName(userName);
            if(user==null){
                model.addAttribute("errMsg", "发生错误");
                return "login";
            }
            session.setAttribute("userName", userName);
            session.setAttribute("role", "user");
            session.setAttribute("id", user.getId());
            session.setAttribute("welcome","Welcome! user: " + userName);
            session.setAttribute("isLogin", true);
            return "redirect:home";
        }
        return "login";
    }

    /**
     *
     * @param userName 用户名
     * @param password 密码
     * @param action   user登录/admin登录
     * @return 登陆成功返回/home，失败返回/login
     * 提交表单后根据button的action来分支选择处理
     * 登陆成功添加session返回首页，失败返回login.jsp
     */
    @PostMapping("/login")
    public String userLogin(@RequestParam("userName") String userName,
                            @RequestParam("password") String password,
                            @RequestParam("action") String action,
                            @RequestParam(value = "rememberMe", required = false) String rememberMe,
                            HttpServletResponse response,
                            HttpSession session, Model model) {
        model.addAttribute("mode", "user");
        User user = loginService.userLogin(userName, password);
        if (user != null) {
            session.setAttribute("userName", userName);
            session.setAttribute("user", user);
            session.setAttribute("role", "user");
            session.setAttribute("id", user.getId());
            session.setAttribute("welcome","Welcome! user:"+userName );
            session.setAttribute("isLogin", true);
            if ("on".equals(rememberMe)) {//如果点击了rememberMe则设置cookie
                Cookie cookie1 = new Cookie("loginUser", "user");
                Cookie cookie2 = new Cookie("userName", userName);
                cookie1.setMaxAge(24 * 60 * 60);//cookie生命周期为1天
                cookie2.setMaxAge(24 * 60 * 60);
                cookie2.setPath("/");
                cookie1.setPath("/");//整个项目都可访问该cookie
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            return "redirect:home";
        }
        else {
            model.addAttribute("errMsg", "用户名不存在或账号密码错误");
        }
        return "/login";//登录失败返回登录页面
    }

    @GetMapping("/admin/login")
    public String adminLogin(Model model,
                             @CookieValue(value = "loginUser", required = false) String loginUser,
                             @CookieValue(value = "userName", required = false) String userName,
                             HttpSession session) {
        model.addAttribute("mode", "admin");
        return "login";
    }

    @PostMapping("/admin/login")
    public String adminLogin(@RequestParam("userName") String userName,
                             @RequestParam("password") String password,
                             @RequestParam("action") String action,
                             @RequestParam(value = "rememberMe", required = false) String rememberMe,
                             HttpServletResponse response,
                             HttpSession session, Model model) {
        Admin admin = loginService.adminLogin(userName, password);
        if (admin != null) {
            session.setAttribute("userName", userName);
            session.setAttribute("role", "admin");
            session.setAttribute("id", admin.getId());
            session.setAttribute("isLogin", true);
            session.setAttribute("welcome","Welcome! admin:"+userName);
            if ("on".equals(rememberMe)) {
                Cookie cookie1 = new Cookie("loginUser", "admin");
                Cookie cookie2 = new Cookie("userName", userName);
                cookie1.setMaxAge(24 * 60 * 60);
                cookie2.setMaxAge(24 * 60 * 60);
                cookie1.setPath("/");
                cookie2.setPath("/");
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            return "redirect:/home";
        } else {
            model.addAttribute("errMsg", "用户名不存在或账号密码错误");
        }
        return "login";//登录失败返回登录页面
    }

    /**
     *
     * @return home
     * 未登陆成功，放弃登录返回首页jsp，不添加session
     */
    @PostMapping("/back")
    public String back(Model model) {
        return "redirect:/home";
    }


    @GetMapping("/changeAccount")
    public String changeAccount(HttpServletResponse response,HttpServletRequest request,HttpSession session) {
        //删除session内容
        session.invalidate();

        //删除cookie内容
        for (Cookie cookie : request.getCookies()) {
            cookie.setValue("");
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return "redirect:login";
    }
}


